# 重写Django的authenetiate 使其支持手机号登录
from django.contrib.auth.backends import ModelBackend
import re
from apps.users.models import User
class AuthModel(ModelBackend):
    # 重写用户验证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断username是否是手机号
        try:
            if re.match(r'1[3-9]\d{9}',username):
                # 按照手机号字段查询
                user = User.objects.get(mobile=username)
            else:
                # 按照用户名字段查询
                user = User.objects.get(username=username)
        except:
            user = None

        if user is not None and user.check_password(password):
            # 校验密码
            return user
        return None